package com.soft.collateral.controller;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.soft.collateral.dto.MenuDTO;
import com.soft.collateral.entity.Menu;
import com.soft.collateral.result.Result;
import com.soft.collateral.service.MenuService;
import com.soft.collateral.utils.JwtHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.soft.collateral.constant.MessageConstant;

import java.util.List;

@RestController
@RequestMapping("/admin/menu")
@Slf4j
@Api(tags = "后台系统-菜单管理接口")
@RequiredArgsConstructor
public class MenuController {

    private final MenuService menuService;

    @ApiOperation("根据当前登录账号获取菜单")
    @GetMapping("get-async-routes")
    public Result getRoutes(@RequestHeader("Authorization") String authorization){

        if(StringUtils.hasLength(authorization)){
            String token = authorization.substring(7);
            Long userId = JwtHelper.getUserId(token);
            List<MenuDTO> list = menuService.findAll(userId);
            if(!CollectionUtils.isEmpty(list)){
                cleanEmptyChildren(list); // 递归去除空children
                return new Result(true , MessageConstant.GET_MENU_SUCCESS , list);
            }
        }
        return new Result(false , MessageConstant.GET_MENU_FAIL);
    }

    private void cleanEmptyChildren(List<MenuDTO> menuList) {
        if (menuList == null) return;
        for (MenuDTO menu : menuList) {
            List<MenuDTO> children = menu.getChildren();
            if (children == null || children.isEmpty()) {
                menu.setChildren(null); // 这样序列化时不会输出children字段
            } else {
                cleanEmptyChildren(children); // 递归处理
            }
        }
    }

    @ApiOperation("获取菜单列表")
    @GetMapping
    public Result list() {
        List<Menu> menus = menuService.getAllMenus();
        return new Result(true, "查询成功", menus);
    }

    @ApiOperation("根据id查询菜单")
    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id) {
        Menu menu = menuService.getMenuById(id);
        return new Result(true, "查询成功", menu);
    }

    @ApiOperation("添加菜单")
    @PostMapping
    public Result add(@RequestBody Menu menu) {
        boolean success = menuService.addMenu(menu);
        if (success) {
            return new Result(true, "新增成功", true);
        } else {
            return new Result(false, "新增失败", false);
        }
    }

    @ApiOperation("修改菜单")
    @PutMapping
    public Result update(@RequestBody Menu menu) {
        boolean success = menuService.updateMenu(menu);
        if (success) {
            return new Result(true, "修改成功", true);
        } else {
            return new Result(false, "修改失败", false);
        }
    }

    @ApiOperation("根据id删除菜单")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean success = menuService.deleteMenu(id);
        if (success) {
            return new Result(true, "删除成功", true);
        } else {
            return new Result(false, "删除失败", false);
        }
    }

    @ApiOperation("根据id删除菜单及对应meta")
    @DeleteMapping("/{id}/cascade")
    public Result deleteCascade(@PathVariable Integer id) {
        boolean success = menuService.deleteMenuCascade(id);
        if (success) {
            return new Result(true, "删除成功", true);
        } else {
            return new Result(false, "删除失败", false);
        }
    }

    // 在 MenuController.java 中添加以下接口：

    @ApiOperation("为菜单分配角色")
    @PostMapping("/{menuId}/assign-roles")
    public Result assignRolesToMenu(@PathVariable Integer menuId, @RequestBody Integer[] roleIds) {
        boolean success = menuService.assignRolesToMenu(menuId, roleIds);
        return success ?
                new Result(true, "角色分配成功", true) :
                new Result(false, "角色分配失败", false);
    }

    @ApiOperation("获取菜单关联的角色ID列表")
    @GetMapping("/{menuId}/roles")
    public Result getRolesByMenuId(@PathVariable Integer menuId) {
        List<Integer> roleIds = menuService.getRoleIdsByMenuId(menuId);
        return new Result(true, "查询成功", roleIds);
    }
}
